package com.example.pan.ui.download

import android.annotation.SuppressLint
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.example.pan.aria2.Aria2Repository
import com.example.pan.model.Aria2GlobalStat
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@HiltViewModel
class DownloadViewModel @Inject constructor(
    private val aria2Repository: Aria2Repository
) : ViewModel() {

    val globalStat = MutableLiveData<Aria2GlobalStat>()

    @SuppressLint("SimpleDateFormat")
    @ExperimentalCoroutinesApi
    fun tellAllTask() = liveData {
        aria2Repository.tellAllTask().catch {
            it.printStackTrace()
            emit(arrayListOf())
        }.collectLatest {
            Log.e(
                "${
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Date())
                }tellAllTask", Gson().toJson(it)
            )
            emit(it)
        }
    }

    @ExperimentalCoroutinesApi
    fun pause(gid: String) = liveData {
        aria2Repository.pause(gid).catch {
            it.printStackTrace()
        }.collectLatest {
            emit(it)
        }
    }


    @ExperimentalCoroutinesApi
    fun unPause(gid: String) = liveData {
        aria2Repository.unPause(gid).catch {
            it.printStackTrace()
        }.collectLatest {
            emit(it)
        }
    }

    @ExperimentalCoroutinesApi
    fun remove(gid: String) = liveData {
        aria2Repository.remove(gid).catch {
            it.printStackTrace()
        }.collectLatest {
            emit(it)
        }
    }

}